﻿using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Client.Subscribing;
using System.Text;
using util_c_sharp.util.mqtt;
using wsacq.com.util;

namespace util_c_sharp.util
{
    internal class UtilMqttBase
    {

        static IMqttClient mqttClient = new MqttFactory().CreateMqttClient();

        internal static IMqttClient CreateMqttClient()
        {
            Console.WriteLine("开始启动mqtt服务......");

            mqttClient.UseDisconnectedHandler(async e =>
            {
                Console.WriteLine("开始尝试重新链接......");
                await Task.Delay(TimeSpan.FromSeconds(5));
            });

            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                Console.WriteLine("消息通知");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
                mqttClient.PublishAsync("hello/world");
            });

            mqttClient.UseConnectedHandler(async e =>
            {
                Console.WriteLine("mqtt 连接成功！");
            });

            mqttClient.ConnectAsync(FactoryMqttOption.InitOptionsOfFm(), CancellationToken.None);

            return mqttClient;
        }

        public static void subMsg(string topic)
        {
            mqttClient.SubscribeAsync(new MqttClientSubscribeOptionsBuilder().WithTopicFilter(topic).Build());
        }


    }
}
